﻿// -----------------------------------------------------------------------
// <copyright file="Utility.cs" company="Microsoft">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

using System;
using System.IO;

namespace EContractServer.SecurityLibrary
{

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class Utility
    {
        // Properties

        // Open and read file
        public static string ReadKeyFile(string p_sFilePath, out int p_iBitStrength )
        {
            string l_sContentFile = string.Empty;
            string l_sBitStrengthString = string.Empty;
            StreamReader l_reader = new StreamReader( p_sFilePath );

            // Initialize
            p_iBitStrength = 0;

            // Reading file
            try
            {
                l_sContentFile = l_reader.ReadToEnd();

                if ( l_sContentFile.Contains( "<BitStrength>" ) )
                {
                    l_sBitStrengthString = l_sContentFile.Substring( 0, l_sContentFile.IndexOf( "</BitStrength>" ) + 14 );
                    l_sContentFile = l_sContentFile.Replace( l_sBitStrengthString, "" );
                    p_iBitStrength = Convert.ToInt32( l_sBitStrengthString.Replace( "<BitStrength>", "" ).Replace( "</BitStrength>", "" ) );
                }
            }
            catch ( Exception Ex )
            {
                // Writing log
                Console.WriteLine( Ex.Message );
            }
            finally
            {
                l_reader.Close();
            }

            return l_sContentFile;
        }

        // Open and read file
        public static string ReadFile( string p_sFilePath )
        {
            string l_sContentFile = string.Empty;
            StreamReader l_reader = new StreamReader( p_sFilePath );

            // Reading file
            try
            {
                l_sContentFile = l_reader.ReadToEnd();
            }
            catch ( Exception Ex )
            {
                // Writing log
                Console.WriteLine( Ex.Message );
            }
            finally
            {
                l_reader.Close();
            }

            return l_sContentFile;
        }

        // Write to file
        public static bool WriteFile( string p_sFilePath, string p_sContent )
        {
            bool l_bResult = false;
            StreamWriter l_writer = new StreamWriter( p_sFilePath );

            try
            {
                l_writer.WriteLine( p_sContent );
            }
            catch ( Exception Ex )
            {
                // Writing log
                Console.WriteLine( Ex.Message );
            }
            finally
            {
                l_writer.Close();
            }

            return l_bResult;
        }
    }
}
